<template>
    <el-dialog title="编辑题目" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false"
        :before-close="handleClose" :append-to-body="true" class="question-editor-dialog">

        <div class="editor-container">
            <!-- 题目类型信息 -->
            <div class="editor-header">
                <el-tag :type="getQuestionTypeTagType(questionType)" size="medium">
                    {{ getQuestionTypeLabel(questionType) }}
                </el-tag>
                <span class="question-count">共 {{ editQuestions.length }} 题</span>
            </div>

            <!-- 题目编辑列表 -->
            <div class="questions-list">
                <div v-for="(question, index) in editQuestions" :key="index" class="question-editor-item">
                    <div class="question-header">
                        <span class="question-number">第 {{ index + 1 }} 题</span>
                        <div class="question-actions">
                            <el-button size="mini" type="primary" icon="el-icon-edit"
                                @click="editSingleQuestion(index)">
                                编辑
                            </el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteQuestion(index)">
                                删除
                            </el-button>
                        </div>
                    </div>

                    <!-- 单选题预览 -->
                    <div v-if="questionType === 'choice'" class="question-preview">
                        <div class="question-text">{{ question.question }}</div>
                        <div class="choices-preview">
                            <div v-for="(choice, choiceIndex) in question.choose" :key="choiceIndex"
                                class="choice-preview" :class="{ 'correct': choice === question.answer }">
                                {{ choice }}
                            </div>
                        </div>
                        <div class="answer-preview">正确答案：{{ question.answer }}</div>
                    </div>

                    <!-- 判断题预览 -->
                    <div v-if="questionType === 'TF'" class="question-preview">
                        <div class="question-text">{{ question.question }}</div>
                        <div class="tf-preview">
                            <span class="tf-option" :class="{ 'correct': question.answer === true }">正确</span>
                            <span class="tf-option" :class="{ 'correct': question.answer === false }">错误</span>
                        </div>
                        <div class="answer-preview">正确答案：{{ question.answer ? '正确' : '错误' }}</div>
                    </div>

                    <!-- 填空题预览 -->
                    <div v-if="questionType === 'fill'" class="question-preview">
                        <div class="question-text">{{ question.question }}</div>
                        <div class="fill-answers-preview">
                            <span v-for="(answer, answerIndex) in question.answer" :key="answerIndex"
                                class="fill-answer">
                                {{ answer }}
                            </span>
                        </div>
                    </div>

                    <!-- 简答题预览 -->
                    <div v-if="questionType === 'answer'" class="question-preview">
                        <div class="question-text">{{ question.question }}</div>
                        <div class="answer-preview">参考答案：{{ question.answer }}</div>
                    </div>

                    <!-- 知识点标签 -->
                    <div class="knowledge-point">
                        <el-tag size="mini" type="info">{{ question.point }}</el-tag>
                    </div>
                </div>
            </div>

            <!-- 添加新题目按钮 -->
            <div class="add-question-section">
                <el-button type="primary" icon="el-icon-plus" @click="addNewQuestion">
                    添加新题目
                </el-button>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="saveChanges">保存修改</el-button>
        </span>

        <!-- 单题编辑对话框 -->
        <QuestionDetailEditor :visible.sync="detailEditorVisible" :question="currentEditQuestion"
            :questionType="questionType" :questionIndex="currentEditIndex" @save="handleSingleQuestionSave" />
    </el-dialog>
</template>

<script>
import QuestionDetailEditor from './QuestionDetailEditor.vue';

export default {
    name: 'QuestionEditor',
    components: {
        QuestionDetailEditor
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        questions: {
            type: Array,
            default: () => []
        },
        questionType: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            dialogVisible: false,
            editQuestions: [],
            detailEditorVisible: false,
            currentEditQuestion: null,
            currentEditIndex: -1,
            hasChanges: false
        }
    },
    watch: {
        visible(newVal) {
            this.dialogVisible = newVal;
            if (newVal) {
                this.initEditQuestions();
            }
        },
        dialogVisible(newVal) {
            if (!newVal) {
                this.$emit('update:visible', false);
            }
        }
    },
    methods: {
        // 初始化编辑题目数据
        initEditQuestions() {
            this.editQuestions = JSON.parse(JSON.stringify(this.questions));
            this.hasChanges = false;
        },

        // 获取题目类型标签文本
        getQuestionTypeLabel(type) {
            const typeMap = {
                'choice': '单选题',
                'TF': '判断题',
                'fill': '填空题',
                'answer': '简答题'
            };
            return typeMap[type] || '未知题型';
        },

        // 获取题目类型标签颜色
        getQuestionTypeTagType(type) {
            const typeMap = {
                'choice': 'primary',
                'TF': 'success',
                'fill': 'warning',
                'answer': 'info'
            };
            return typeMap[type] || 'info';
        },

        // 编辑单个题目
        editSingleQuestion(index) {
            this.currentEditQuestion = JSON.parse(JSON.stringify(this.editQuestions[index]));
            this.currentEditIndex = index;
            this.detailEditorVisible = true;
        },

        // 处理单个题目保存
        handleSingleQuestionSave(questionData) {
            this.editQuestions[this.currentEditIndex] = questionData;
            this.hasChanges = true;
            this.detailEditorVisible = false;
            this.$message.success('题目修改成功');
        },

        // 删除题目
        deleteQuestion(index) {
            this.$confirm('确定要删除这道题目吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.editQuestions.splice(index, 1);
                this.hasChanges = true;
                this.$message.success('题目删除成功');
            }).catch(() => {
                // 用户取消删除
            });
        },

        // 添加新题目
        addNewQuestion() {
            const newQuestion = this.createEmptyQuestion(this.questionType);
            this.editQuestions.push(newQuestion);
            this.hasChanges = true;
            // 直接编辑新添加的题目
            this.editSingleQuestion(this.editQuestions.length - 1);
        },

        // 创建空白题目模板
        createEmptyQuestion(type) {
            const baseQuestion = {
                question: '',
                point: '',
                answer: ''
            };

            switch (type) {
                case 'choice':
                    return {
                        ...baseQuestion,
                        choose: ['A. ', 'B. ', 'C. ', 'D. '],
                        answer: 'A. '
                    };
                case 'TF':
                    return {
                        ...baseQuestion,
                        answer: true
                    };
                case 'fill':
                    return {
                        ...baseQuestion,
                        answer: ['']
                    };
                case 'answer':
                default:
                    return baseQuestion;
            }
        },

        // 保存修改
        saveChanges() {
            if (!this.hasChanges) {
                this.$message.info('没有检测到修改');
                this.handleClose();
                return;
            }

            this.$emit('save', {
                type: this.questionType,
                questions: this.editQuestions
            });
            this.hasChanges = false;
            this.handleClose();
            this.$message.success('题目保存成功');
        },

        // 关闭对话框
        handleClose() {
            if (this.hasChanges) {
                this.$confirm('有未保存的修改，确定要关闭吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.dialogVisible = false;
                }).catch(() => {
                    // 用户取消关闭
                });
            } else {
                this.dialogVisible = false;
            }
        }
    }
}
</script>

<style scoped>
.question-editor-dialog :deep(.el-dialog) {
    margin-top: 5vh !important;
    z-index: 2000 !important;
}

.question-editor-dialog :deep(.el-dialog__wrapper) {
    z-index: 2000 !important;
}

.editor-container {
    max-height: 70vh;
    overflow-y: auto;
}

.editor-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 12px 16px;
    background: linear-gradient(135deg, #f6f9fc 0%, #e9f4ff 100%);
    border-radius: 8px;
    border: 1px solid #d9ecff;
}

.question-count {
    color: #666;
    font-size: 14px;
    font-weight: 500;
}

.questions-list {
    margin-bottom: 20px;
}

.question-editor-item {
    margin-bottom: 20px;
    padding: 16px;
    background: #fafbfc;
    border: 1px solid #e1e4e8;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.question-editor-item:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.question-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;
}

.question-number {
    font-weight: 600;
    color: #409eff;
    font-size: 16px;
}

.question-actions {
    display: flex;
    gap: 8px;
}

.question-preview {
    margin-bottom: 12px;
}

.question-text {
    font-size: 14px;
    line-height: 1.6;
    color: #303133;
    margin-bottom: 12px;
    font-weight: 500;
}

.choices-preview {
    margin-bottom: 8px;
}

.choice-preview {
    padding: 4px 8px;
    margin: 2px 0;
    background: #f8f9fa;
    border-radius: 4px;
    font-size: 13px;
}

.choice-preview.correct {
    background: #f0f9ff;
    color: #409eff;
    font-weight: 500;
}

.tf-preview {
    display: flex;
    gap: 12px;
    margin-bottom: 8px;
}

.tf-option {
    padding: 4px 12px;
    background: #f8f9fa;
    border-radius: 4px;
    font-size: 13px;
}

.tf-option.correct {
    background: #f0f9ff;
    color: #409eff;
    font-weight: 500;
}

.fill-answers-preview {
    margin-bottom: 8px;
}

.fill-answer {
    display: inline-block;
    padding: 2px 8px;
    margin: 2px 4px;
    background: #e8f5e8;
    color: #67c23a;
    border-radius: 3px;
    font-size: 13px;
}

.answer-preview {
    font-size: 13px;
    color: #409eff;
    font-weight: 500;
}

.knowledge-point {
    margin-top: 8px;
}

.add-question-section {
    text-align: center;
    padding: 20px;
    border: 2px dashed #e4e7ed;
    border-radius: 8px;
    background: #fafbfc;
}

.add-question-section:hover {
    border-color: #409eff;
    background: #f0f9ff;
}

/* 滚动条样式 */
.editor-container::-webkit-scrollbar {
    width: 6px;
}

.editor-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.editor-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.editor-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>
